package com.jic.market.impl.rest.groupon;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.common.utils.CronUtil;
import com.jic.common.utils.DateUtils;
import com.jic.common.utils.HttpClientUtils;
import com.jic.common.utils.IDUtils;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.common.enums.MutexFlagEnum;
import com.jic.market.common.enums.TypeOfProductEnum;
import com.jic.market.common.exception.MarketErrorCodeEnum;
import com.jic.market.common.exception.MarketException;
import com.jic.market.entity.*;
import com.jic.market.enums.*;
import com.jic.market.job.entity.JobExecutorParam;
import com.jic.market.job.entity.RestCreateJobRequest;
import com.jic.market.mapper.*;
import com.jic.market.model.LimitQueryUniqueCondition;
import com.jic.market.orm.Pagination;
import com.jic.market.request.manager.patchgroup.PatchGrouponInstForceGroupRequest;
import com.jic.market.request.rest.bargain.MyBargainResponse;
import com.jic.market.request.rest.groupon.*;
import com.jic.market.response.rest.groupon.*;
import com.jic.market.service.*;
import com.jic.market.service.rest.groupon.GrouponRestService;
import com.jic.order.api.OrderApi;
import com.jic.order.response.OrderDetailInfo;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xuyongliang
 * @version V1.0
 * @className GrouponRestServiceImpl
 * @description 拼团活动H5服务
 * @date 2020/4/8
 */
@Slf4j
@Service
@RefreshScope
public class GrouponRestServiceImpl implements GrouponRestService {

    private final static Integer PROMOTION_START =1;
    private final static Integer PROMOTION_LIMIT =1;

    private final static Integer PRODUCT_START =1;
    private final static Integer PRODUCT_LIMIT =100;

    @Value("${market.value.job.host}")
    private String jobHost;

    @Value("${market.value.job.autoCompleteGroupHost}")
    private String autoCompleteGroupHost;

    @Resource
    private PatchGrouponThemeEntityMapper patchGrouponThemeEntityMapper;

    @Resource
    private PatchGrouponDetailEntityMapper patchGrouponDetailEntityMapper;

    @Resource
    private PatchGroupMerchantProductService merchantProductService;

    @Resource
    private PatchGrouponStockLmtService stockLmtEntityService;

    @Resource
    private PatchGrouponInstService patchGrouponInstService;

    @Resource
    private PatchGrouponInstDetailService patchGrouponInstDetailService;

    @Autowired
    private PatchGrouponMpEntityMapper patchGrouponMpEntityMapper;

    @Autowired
    private PatchGrouponStockLmtEntityMapper patchGrouponStockLmtEntityMapper;

    @Resource
    private ProductListApi productListApi;

    @Autowired
    private PromotionMyBargainMapper myBargainMapper;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @Resource
    private OrderApi orderApi;
    /**
     * 购买数量默认值
     */
    private final static Integer BUY_NUM =1;

    /**
     *  job 返回200 为成功
     */
    private final static String JOB_RETURN_CODE = "200";


    @Override
    public RestResult<PageResult<GrouponInfoResponse>> grouponList(GrouponListRequest request) {
        try {
            Pagination pagination = Pagination.build(request.getStart(),request.getLimit() );
            PatchGrouponThemeMpQuery param = new PatchGrouponThemeMpQuery();
            param.setChildId(request.getAdminOperate() != null ? request.getAdminOperate().getChildId() : null);

            param.setTypeOfProduct(request.getProductType() == null ? PromotionProductTypeEnum.TYPE_SPU.getType() : request.getProductType());
            param.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
            List<PatchGrouponThemeMpEntity> themeMpEntities = patchGrouponMpEntityMapper.getIngThemeMps(param, pagination);


            List<GrouponInfoResponse> spuRestResponseList = new ArrayList<>();

            if(CollectionUtils.isNotEmpty(themeMpEntities)){
                for (PatchGrouponThemeMpEntity productEntity : themeMpEntities) {
                    List<GrouponInfoResponse> skuResponses = null;
                    //如果下级SKU没有生效的则跳出
                    if(PromotionProductTypeEnum.TYPE_SPU.getType().equals(productEntity.getTypeOfProduct())){
                        Integer count = patchGrouponMpEntityMapper.getSkuCount(productEntity.getPromotionId(),productEntity.getMpId());
                        if(count == 0){
                            break;
                        }
                    }
                    //查询所有生效sku列表 默认不传时 查出下级SKU
                    if(request.getProductType() == null){
                        PatchGrouponMpEntity skuParam = new PatchGrouponMpEntity();
                        skuParam.setPromotionId(productEntity.getPromotionId());
                        skuParam.setTypeOfProduct(PromotionProductTypeEnum.TYPE_SKU.getType());
                        skuParam.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                        skuParam.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
                        skuParam.setMpParentId(productEntity.getMpId());
                        List<PatchGrouponMpEntity> skuEntitys = patchGrouponMpEntityMapper.findAll(skuParam);
                        PatchGrouponStockLmtEntity grouponStockLmtEntitySku = new PatchGrouponStockLmtEntity();
                        grouponStockLmtEntitySku.setPatchGrouponMpId(productEntity.getPatchGrouponMpId());
                        grouponStockLmtEntitySku.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                        PatchGrouponStockLmtEntity patchGrouponStockLmtEntitySku = patchGrouponStockLmtEntityMapper.query(grouponStockLmtEntitySku);

                        skuResponses = skuEntitys.stream().map(s->{
                            return new GrouponInfoResponse()
                                    .setThirdProductCode(s.getThirdSpuSkuId())
                                    .setEndTime(productEntity.getEndTime().getTime())
                                    .setEndTimeStr(DateUtils.convert(productEntity.getEndTime()))
                                    .setStartTime(productEntity.getStartTime().getTime())
                                    .setStartTimeStr(DateUtils.convert(productEntity.getStartTime()))
                                    .setGroupCode(productEntity.getGroupCode())
                                    .setGroupMembers(productEntity.getGroupMembers())
                                    .setPromName(productEntity.getPromName())
                                    .setPromPicUrl(StringUtils.isNotBlank(productEntity.getFileUrl())?productEntity.getFileUrl().split(",")[0]:null)
                                    .setMarketPrice(productEntity.getSalePrice())
                                    .setMarketPriceScope(productEntity.getSalePriceScope())
                                    .setAvailablePrice(patchGrouponStockLmtEntitySku != null ? patchGrouponStockLmtEntitySku.getGrouponPrice() : null)
                                    .setMpName(s.getMpName());
                        }).collect(Collectors.toList());
                    }

                    PatchGrouponStockLmtEntity grouponStockLmtEntity = new PatchGrouponStockLmtEntity();
                    grouponStockLmtEntity.setPatchGrouponMpId(productEntity.getPatchGrouponMpId());
                    grouponStockLmtEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                    PatchGrouponStockLmtEntity patchGrouponStockLmtEntity = patchGrouponStockLmtEntityMapper.query(grouponStockLmtEntity);
                    spuRestResponseList.add(
                            new GrouponInfoResponse()
                                    .setThirdProductCode(productEntity.getThirdSpuSkuId())
                                    .setEndTime(productEntity.getEndTime().getTime())
                                    .setEndTimeStr(DateUtils.convert(productEntity.getEndTime()))
                                    .setStartTime(productEntity.getStartTime().getTime())
                                    .setStartTimeStr(DateUtils.convert(productEntity.getStartTime()))
                                    .setGroupCode(productEntity.getGroupCode())
                                    .setGroupMembers(productEntity.getGroupMembers())
                                    .setPromName(productEntity.getPromName())
                                    .setPromPicUrl(StringUtils.isNotBlank(productEntity.getFileUrl())?productEntity.getFileUrl().split(",")[0]:null)
                                    .setMpName(productEntity.getMpName())
                                    .setMarketPrice(productEntity.getSalePrice())
                                    .setMarketPriceScope(productEntity.getSalePriceScope())
                                    .setAvailablePrice(patchGrouponStockLmtEntity != null ? patchGrouponStockLmtEntity.getGrouponPrice() : null)
                                    .setChildrenProductList(skuResponses)
                    );
                }
            }
            long total = patchGrouponMpEntityMapper.countIngThemeMps(param);
            return RestResult.success(new PageResult<GrouponInfoResponse>(){{
                setRows(spuRestResponseList);
                setTotal(total);
            }});
        }catch (Exception e){
            log.error("========拼团活动列表发生错误========{}",e);
            return RestResult.error("9999","服务器错误");
        }
    }

    @Override
    public RestResult<GrouponInfoResponse> grouponInfo(GrouponInfoRequest request) {
        try {
            GrouponInfoResponse grouponInfoResponse = new GrouponInfoResponse();
            PatchGrouponThemeEntity param = new PatchGrouponThemeEntity();
            param.setGroupCode(request.getGroupCode());
            PatchGrouponThemeEntity patchGrouponThemeEntity = patchGrouponThemeEntityMapper.query(param);

            grouponInfoResponse.setEndTime(patchGrouponThemeEntity.getEndTime().getTime());
            grouponInfoResponse.setEndTimeStr(DateUtils.convert(patchGrouponThemeEntity.getEndTime()));
            grouponInfoResponse.setStartTime(patchGrouponThemeEntity.getStartTime().getTime());
            grouponInfoResponse.setStartTimeStr(DateUtils.convert(patchGrouponThemeEntity.getStartTime()));
            grouponInfoResponse.setGroupCode(patchGrouponThemeEntity.getGroupCode());
            grouponInfoResponse.setGroupMembers(patchGrouponThemeEntity.getGroupMembers());
            grouponInfoResponse.setPromName(patchGrouponThemeEntity.getPromName());
            if(StringUtils.isNotBlank(patchGrouponThemeEntity.getFileUrl())){
                grouponInfoResponse.setPromPicUrl(patchGrouponThemeEntity.getFileUrl().split(",")[0]);
            }

            //查询参与商品
            PatchGrouponMpEntity mpEntity = new PatchGrouponMpEntity();
            mpEntity.setPromotionId(patchGrouponThemeEntity.getId());
            mpEntity.setThirdSpuSkuId(request.getThirdProductCode());
            mpEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            mpEntity.setTypeOfProduct(request.getProductType());
            PatchGrouponMpEntity patchGrouponMpEntity = patchGrouponMpEntityMapper.query(mpEntity);
            grouponInfoResponse.setThirdProductCode(patchGrouponMpEntity.getThirdSpuSkuId());
            grouponInfoResponse.setMpName(patchGrouponMpEntity.getMpName());
            if(PromotionProductTypeEnum.TYPE_SKU.getType().equals(request.getProductType())){
                grouponInfoResponse.setMarketPrice(patchGrouponMpEntity.getSalePrice());
            }else if(PromotionProductTypeEnum.TYPE_SPU.getType().equals(request.getProductType())){
                grouponInfoResponse.setMarketPriceScope(patchGrouponMpEntity.getSalePriceScope());
            }

            //获取拼团价
            PatchGrouponStockLmtEntity grouponStockLmtEntity = new PatchGrouponStockLmtEntity();
            grouponStockLmtEntity.setPatchGrouponMpId(patchGrouponMpEntity.getId());
            grouponStockLmtEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            PatchGrouponStockLmtEntity patchGrouponStockLmtEntity = patchGrouponStockLmtEntityMapper.query(grouponStockLmtEntity);
            grouponInfoResponse.setAvailablePrice(patchGrouponStockLmtEntity != null ? patchGrouponStockLmtEntity.getGrouponPrice() : null);
            return RestResult.success(grouponInfoResponse);
        }catch (Exception e){
            log.error("========拼团活动详情发生错误========{}",e);
            return RestResult.error("9999","服务器错误");
        }
    }

    @Override
    public LaunchOrJoinGrouponResponse launchOrJoinGrouponCheck(
            LaunchOrJoinGrouponRequest request) {
        log.info("------进入拼团活动H5服务--开参团活动校验--参数为:{}-----",request);
        // 【步骤】校验活动及活动时间
        PatchGrouponThemeEntity themeCondition =new PatchGrouponThemeEntity();
        themeCondition.setGroupCode(request.getGroupCode());
        PatchGrouponThemeEntity themeEntity = patchGrouponThemeEntityMapper.query(themeCondition);
        if(themeEntity == null){
            log.info("------拼团活动H5服务--开参团活动校验--无此活动信息--活动编码{}---",request.getGroupCode());
            throw new MarketException(MarketErrorCodeEnum.GROUP_NO_PROM_INFO);
        }
        // 【步骤】校验开团开始与结束时间，当前时间在二者之间    --需要判断参团才校验
        Date themeStartTime = themeEntity.getStartTime();
        Date themeEndTime = themeEntity.getEndTime();
        Date currentDate =new Date();
        if(!(currentDate.getTime()>= themeStartTime.getTime() && currentDate.getTime()<=themeEndTime.getTime())){
            log.info("------拼团活动H5服务--开参团活动校验--不在活动时间内--活动编码{}---",request.getGroupCode());
            throw new MarketException(MarketErrorCodeEnum.GROUP_NOT_IN_PROM_TIME);
        }

        // 【步骤】根据第三方商品编码，活动编码，查询商品id
        PatchGrouponMpEntity mpCondition =new PatchGrouponMpEntity();
        mpCondition.setPromotionId(themeEntity.getId());
        mpCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
//        mpCondition.setThirdSpuSkuId(request.getThirdProductCode());
        mpCondition.setMpId(request.getMpId());
        mpCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        PatchGrouponMpEntity mpEntity = merchantProductService.query(mpCondition);
        Long mpId = mpEntity.getMpId();
        Integer typeOfProduct = mpEntity.getTypeOfProduct();
        Long promotionId = mpEntity.getPromotionId();
        Long storeId = mpEntity.getStoreId();

        // 【步骤】 根据patch_groupon_mp id 查询 patch_groupon_stock_lmt  信息 取出限购信息 order_limit，individual_limit，channel_store_limit，channel_merchant_limit
        LimitQueryUniqueCondition limitQueryUniqueCondition =new LimitQueryUniqueCondition();
        limitQueryUniqueCondition.setMpId(mpId);
        limitQueryUniqueCondition.setTypeOfProduct(typeOfProduct);
        limitQueryUniqueCondition.setPromotionId(promotionId);
        limitQueryUniqueCondition.setStoreId(storeId);
        PatchGrouponStockLmtEntity stockLimitRule = stockLmtEntityService.getEntityLimitQueryUniqueCondition(limitQueryUniqueCondition);
        Long channelMerchantLimit = stockLimitRule.getChannelMerchantLimit();
        Long channelStoreLimit = stockLimitRule.getChannelStoreLimit();
        Long individualLimit = stockLimitRule.getIndividualLimit();
        Integer orderLimit = stockLimitRule.getOrderLimit();

        // 【步骤】查询拼团实例详情列表  patch_groupon_detail  过滤条件，third_product_code  group_code
        PatchGrouponDetailEntity instDetailCondition =new PatchGrouponDetailEntity();
        List<Integer> statusList =new ArrayList<>();
        statusList.add(GrouponDetailPaymentStatusEnum.PAY_NOT.getCode());
        statusList.add(GrouponDetailPaymentStatusEnum.PAY_HAVE.getCode());
        instDetailCondition.setPaymentStatusList(statusList);

        instDetailCondition.setThirdProductCode(request.getThirdProductCode());
        instDetailCondition.setGroupCode(instDetailCondition.getGroupCode());
        instDetailCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        List<PatchGrouponDetailEntity> detailEntityList = patchGrouponInstDetailService.findAll(instDetailCondition);
        Integer instDetailSize =0;
        if(detailEntityList != null ){
            instDetailSize = detailEntityList.size();
        }

        // 【步骤】校验店铺限制商品数量
        if(channelStoreLimit != null && instDetailSize +1 >channelStoreLimit){
            log.info("------拼团活动H5服务--开参团活动校验--超过店铺限制--第三方商品编码:{}--拼团实例code:{}--活动编码:{}-----",request.getThirdProductCode(), request.getGrouponInstCode(), request.getGroupCode());
            throw new MarketException(MarketErrorCodeEnum.GROUP_STORE_LIMIT);
        }

        // 【步骤】校验用户单渠道限制
        Integer userHasBuyCount = detailEntityList.stream().filter(item ->
                item.getThirdUserId().equals(request.getThirdUserId())).collect(Collectors.toList()).stream()
                .mapToInt(PatchGrouponDetailEntity::getBuyNum).sum();
        if(individualLimit != null && userHasBuyCount + 1 > individualLimit){
            log.info("------拼团活动H5服务--开参团活动校验--用户单渠道限制--第三方商品编码:{}--拼团实例code:{}--活动编码:{}-----",request.getThirdProductCode(), request.getGrouponInstCode(), request.getGroupCode());
            throw new MarketException(MarketErrorCodeEnum.GROUP_INDIVIDUAL_LIMIT);
        }

        if(GrouponLaunchFlag.GROUP_JOIN.getCode().equals(request.getLaunchFlag())){
            // 【步骤】校验是否成团   patch_groupon_inst  status
            PatchGrouponInstEntity instEntityCondition =new PatchGrouponInstEntity();
            instEntityCondition.setGrouponInstCode(request.getGrouponInstCode());

            // 通过拼团实例code 查询
            PatchGrouponInstEntity instEntity = patchGrouponInstService.queryEntity(instEntityCondition);
            if(instEntity !=null){
                Integer instEntityStatus = instEntity.getStatus();
                Integer joinedMembers = instEntity.getJoinedMembers();
                Integer totalMembers = instEntity.getTotalMembers();
                if(GrouponInstStatusEnum.GROUPED.getCode().equals(instEntityStatus)){
                    log.info("------拼团活动H5服务--开参团活动校验--已经成团--拼团实例code:{}--活动编码:{}-----",request.getGrouponInstCode(), request.getGroupCode());
                    throw new MarketException(MarketErrorCodeEnum.GROUP_HAS_CIRCLE);
                }

                // 【步骤】参团人数是否达到最大团员人数
                if (joinedMembers +1 >totalMembers){
                    log.info("------拼团活动H5服务--开参团活动校验--参团人数已经到最大团员人数--拼团实例code:{}--活动编码:{}-----",request.getGrouponInstCode(), request.getGroupCode());
                    throw new MarketException(MarketErrorCodeEnum.GROUP_HAS_FULL_NUM);
                }

            }
        }

        // TODO 校验开团对象限制        --需要判断开团才校验

        // TODO 校验参团对象限制        --需要判断参团才校验

        // 【步骤】校验库存是否充足
//        GoodsSku goodsSku = goodsSkuService.queryByPrimaryKey(mpId);
//        if(goodsSku.getStock() <= 0){
//            log.info("------拼团活动H5服务--开参团活动校验--该商品库存为0--第三方商品编码:{},--活动编码:{}---", request.getThirdProductCode(), request.getGroupCode());
//            throw new MarketException(MarketErrorCodeEnum.GROUP_STOCK_ZORE);
//        }

        Integer userHasJoinCount = detailEntityList.stream().filter(item ->
                item.getThirdUserId().equals(request.getThirdUserId())).collect(Collectors.toList()).size();
        // 【步骤】校验用户参加活动是否有限制，如果有检验用户参与活动的次数
        Integer individualJoinType = themeEntity.getIndividualJoinType();
        if(IndividualJoinTypeEnum.RESTRICT_YES.getCode().equals(individualJoinType)){
            // 【步骤】查询该用户参与该活动的次数   patch_groupon_detail 根据  third_user_id  payment_status  支付状态：0未支付，1已支付
            PatchGrouponDetailEntity detailEntityCondition =new PatchGrouponDetailEntity();

            List<Integer> statusListTow =new ArrayList<>();
            statusListTow.add(GrouponDetailPaymentStatusEnum.PAY_NOT.getCode());
            statusListTow.add(GrouponDetailPaymentStatusEnum.PAY_HAVE.getCode());
            detailEntityCondition.setPaymentStatusList(statusListTow);
            detailEntityCondition.setThirdUserId(request.getThirdUserId());
            detailEntityCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            List<PatchGrouponDetailEntity> detailEntityListTow = patchGrouponInstDetailService.findAll(detailEntityCondition);

            Integer individualJoinTime = themeEntity.getIndividualJoinTime();
            Integer currentCount =detailEntityListTow.size();
            if(currentCount +1 > individualJoinTime){
                log.info("------拼团活动H5服务--开参团活动校验--该用户大于个人参团限制次数--第三方用户编码:{}--第三方商品编码:{},--活动编码:{}----", request.getThirdUserId(), request.getThirdProductCode(), request.getGroupCode());
                throw new MarketException(MarketErrorCodeEnum.GROUP_JOIN_TIME);
            }
        }

        // TODO 校验单次购买该商品的数量（待定）
        LaunchOrJoinGrouponResponse innerResp =new LaunchOrJoinGrouponResponse();
        innerResp.setLaunchOrJoinSuccess(Boolean.TRUE);
        return innerResp;
    }

    @Transactional
    @Override
    public LaunchOrJoinGrouponResponse launchOrJoinGroupon(LaunchOrJoinGrouponRequest request) {
        log.info("------拼团活动H5服务--开参团活动--参数为:{}-------", request);
        LaunchOrJoinGrouponResponse innerResp =new LaunchOrJoinGrouponResponse();
        // 【步骤】调用校验接口
        LaunchOrJoinGrouponResponse checkResult = this.launchOrJoinGrouponCheck(request);
        if(!checkResult.getLaunchOrJoinSuccess()){
            return checkResult;
        }

        // 【步骤】查询活动信息
        PatchGrouponThemeEntity themeCondition =new PatchGrouponThemeEntity();
        themeCondition.setGroupCode(request.getGroupCode());
        PatchGrouponThemeEntity themeEntity = patchGrouponThemeEntityMapper.query(themeCondition);
        Long themeId = themeEntity.getId();
        Integer groupMembers = themeEntity.getGroupMembers();
        Integer autoCompleteTime = themeEntity.getAutoCompleteTime();
        Integer groupTimeLimit = themeEntity.getGroupTimeLimit();
        // 活动名称
        String promName = themeEntity.getPromName();

        // 【步骤】查询商品信息
        PatchGrouponMpEntity mpCondition =new PatchGrouponMpEntity();
        mpCondition.setPromotionId(themeEntity.getId());
        mpCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
        mpCondition.setMpId(request.getMpId());
//        mpCondition.setThirdSpuSkuId(request.getThirdProductCode());
        mpCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        PatchGrouponMpEntity mpEntity = merchantProductService.query(mpCondition);
        Long mpId = mpEntity.getMpId();
        Long merchantId = mpEntity.getMerchantId();
        Long storeId = mpEntity.getStoreId();

        // 【步骤】 如果是开团，则在拼团实例表 patch_groupon_inst，插⼀条记录
        if(GrouponLaunchFlag.GROUP_OPEN.getCode().equals(request.getLaunchFlag())){
            PatchGrouponInstEntity instEntity =new PatchGrouponInstEntity();
            instEntity.setRefPatchGrouponTheme(themeId);
            instEntity.setGroupCode(request.getGroupCode());
            instEntity.setLaunchTime(new Date());
            instEntity.setStatus(GrouponInstStatusEnum.GROUP_ING.getCode());
            instEntity.setTotalMembers(groupMembers);
            instEntity.setJoinedMembers(1);

            // 从活动设置中获取拼团时长
            Date expireTime = null;
            Integer groupTimeType = themeEntity.getGroupTimeType();
            if(GroupTimeTypeEnum.TIME_RESTRICT.getCode().equals(groupTimeType)){
                // 【步骤】 设置拼团失效时间
                expireTime = DateUtils.addHours(instEntity.getLaunchTime(), groupTimeLimit);
                instEntity.setExpireTime(expireTime);
            }

//            instEntity.setCompletedTime();
//            instEntity.setCatptainId();
//            instEntity.setCatptainDiscount();
            instEntity.setMpId(mpId);
            instEntity.setMerchantId(merchantId);
            instEntity.setStoreId(storeId);

            instEntity.setGrouponInstCode(IDUtils.GenerateBillNo());

            instEntity.setThirdProductCode(request.getThirdProductCode());
            instEntity.setThirdUserId(request.getThirdUserId());
            instEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            patchGrouponInstService.addInstEntity(instEntity);

            // 【步骤】 在表patch_groupon_detail 插入一条记录  团长 flag，
            PatchGrouponDetailEntity detailEntity =new PatchGrouponDetailEntity();
            detailEntity.setRefPatchGrouponInst(instEntity.getId());
            detailEntity.setRefPatchGrouponTheme(themeId);
            detailEntity.setMpId(mpId);
            detailEntity.setMerchantId(merchantId);
            detailEntity.setStoreId(storeId);

            detailEntity.setGrouponInstCode(instEntity.getGrouponInstCode());
            detailEntity.setGrouponInstDetailCode(IDUtils.GenerateBillNo());

            detailEntity.setThirdProductCode(request.getThirdProductCode());
            detailEntity.setThirdUserId(request.getThirdUserId());
            // 购买数量
            detailEntity.setBuyNum(BUY_NUM);
//            detailEntity.setReceiveMember();
//            detailEntity.setReceiveAddress();
//            detailEntity.setCustomerId();
//            detailEntity.setCellPhone();
//            detailEntity.setDeviceMac();
//            detailEntity.setSourceRef();
            // 订单号
//            detailEntity.setOrderCode();
            // 需要在数据库里添加 third_order_code 然后再设置值
            detailEntity.setThirdOrderCode(request.getThirdOrderCode());
            // 在数据库里添加 group_code 然后再设置值
            detailEntity.setGroupCode(request.getGroupCode());
            detailEntity.setJoinTime(new Date());
//            detailEntity.setStatus();
            detailEntity.setPaymentType(GrouponDetailPaymentTypeEnum.TYPE_ONLINE.getCode());
            detailEntity.setPaymentStatus(GrouponDetailPaymentStatusEnum.PAY_NOT.getCode());
            detailEntity.setIsVirtual(GrouponVirtualEnum.TYPE_REAL.getCode());
//            detailEntity.setIsAvailable();
//            detailEntity.setCompanyId();
            // 设置是否是团长标识
            detailEntity.setHeadFlag(GrouponHeadFlagEnum.GROUP_HEAD.getCode());
            detailEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            patchGrouponInstDetailService.addDetailEntity(detailEntity);
            innerResp.setGrouponInstCode(detailEntity.getGrouponInstCode());

            // 【步骤】 如果是自动成团时间大于0  则调用  开团结束 job
            if(GroupTimeTypeEnum.TIME_RESTRICT.getCode().equals(groupTimeType) && autoCompleteTime > 0 ){
                // 自动拼团时间
                Date autoTime = DateUtils.addHours(instEntity.getExpireTime(), -autoCompleteTime);
                String cron = CronUtil.getCron(autoTime);
                // job平台定时任务请求业务方API接口参数信息
                PatchGrouponInstForceGroupRequest params = new PatchGrouponInstForceGroupRequest();
                params.setPatchGrouponInstId(instEntity.getId());
                String apiParams = JSON.toJSONString(params);

                // job平台定时任务请求业务方请求地址信息
                JobExecutorParam jobExecutorParam = new JobExecutorParam();
                jobExecutorParam.setUrl(autoCompleteGroupHost);
                jobExecutorParam.setMethod("post"); // post and get
                jobExecutorParam.setData(apiParams);

                // job平台REST full API 创建job接口信息
                RestCreateJobRequest jobRequest = new RestCreateJobRequest();
                // 任务负责人 必填
                jobRequest.setAuthor("开团人："+request.getThirdUserId());
                // 任务重试重试次数  非必填
                jobRequest.setExecutorFailRetryCount(2);
                // job平台定时任务HTTP请求业务方接口参数  非必填
                jobRequest.setExecutorParam(jobExecutorParam.toString());
                // 任务执行时间 秒  非必填
                jobRequest.setExecutorTimeout(180);
                // 任务描述 必填  活动名称 + 第三方用户id
                jobRequest.setJobDesc(promName +":"+ request.getThirdUserId());
                // 任务执行器名称 必填，可配置的参数，目前测试环境使用该值：job-executor
                jobRequest.setJobGroupAppName("job-executor");
                // 活动开始时间表达式 必填
                jobRequest.setJobStartCron(cron);
                // 活动结束时间表达式 非必填
//                jobRequest.setJobEndCron("59 59 23 5 5 ?");

                String httpParams = JSON.toJSONString(request);

                try {
                    String result = HttpClientUtils.doPost(jobHost,httpParams);
                    log.info("=======远程调用job返回参数:{}========"+result);
                    // {"code":200,"msg":null,"content":"9"}
                    // code 200 成功
//                    JobReturn jobReturn = JSON.parseObject(result, JobReturn.class);
//                    if(!JOB_RETURN_CODE.equals(jobReturn)){
//
//                    }
                } catch (IOException e) {
                    log.error("-------远程调用拼团job失败-------",e);
                    throw new MarketException(MarketErrorCodeEnum.GROUP_LAUNCH_JOB);
                }
            }

        }else {
            // 【步骤】如果是参团，校验在拼团实例表 patch_groupon_inst，是否存在⼀条记录，根据拼团实例code
            PatchGrouponInstEntity instEntityCondition =new PatchGrouponInstEntity();
            instEntityCondition.setGrouponInstCode(request.getGrouponInstCode());
            // 通过拼团实例code 查询
            PatchGrouponInstEntity instEntity = patchGrouponInstService.queryEntity(instEntityCondition);
            // 【步骤】如果不存在，则该活动商品无开团信息
            if(instEntity == null){
                log.info("------拼团活动H5服务--开参团活动--无此开团信息--拼团实例编码:{}--第三方商品编码:{}--活动编码:{}----",request.getGrouponInstCode(), request.getThirdProductCode(), request.getGroupCode());
                throw new MarketException(MarketErrorCodeEnum.GROUP_NO_INST_INFO);
            }

            // 【步骤】在表patch_groupon_detail 插入一条记录  团员 flag，
            PatchGrouponDetailEntity detailEntity =new PatchGrouponDetailEntity();
            detailEntity.setRefPatchGrouponInst(instEntity.getId());
            detailEntity.setRefPatchGrouponTheme(themeId);
            detailEntity.setMpId(mpId);
            detailEntity.setMerchantId(merchantId);
            detailEntity.setStoreId(storeId);

            detailEntity.setGrouponInstCode(request.getGrouponInstCode());
            detailEntity.setGrouponInstDetailCode(IDUtils.GenerateBillNo());

            detailEntity.setThirdProductCode(request.getThirdProductCode());
            detailEntity.setThirdUserId(request.getThirdUserId());
            // 购买数量
            detailEntity.setBuyNum(BUY_NUM);
//            detailEntity.setReceiveMember();
//            detailEntity.setReceiveAddress();
//            detailEntity.setCustomerId();
//            detailEntity.setCellPhone();
//            detailEntity.setDeviceMac();
//            detailEntity.setSourceRef();
            // 订单号
//            detailEntity.setOrderCode();
            // 需要在数据库里添加 third_order_code 然后再设置值
            detailEntity.setThirdOrderCode(request.getThirdOrderCode());
            // 在数据库里添加 group_code 然后再设置值
            detailEntity.setGroupCode(request.getGroupCode());
            detailEntity.setJoinTime(new Date());
//            detailEntity.setStatus();
            detailEntity.setPaymentType(GrouponDetailPaymentTypeEnum.TYPE_ONLINE.getCode());
            detailEntity.setPaymentStatus(GrouponDetailPaymentStatusEnum.PAY_NOT.getCode());
            detailEntity.setIsVirtual(GrouponVirtualEnum.TYPE_REAL.getCode());
//            detailEntity.setIsAvailable();
//            detailEntity.setCompanyId();
            // 设置是否是团长标识
            detailEntity.setHeadFlag(GrouponHeadFlagEnum.GROUP_MEMBER.getCode());
            detailEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            patchGrouponInstDetailService.addDetailEntity(detailEntity);
            innerResp.setGrouponInstCode(detailEntity.getGrouponInstCode());

            // 【步骤】 修改patch_groupon_inst 参团人数数量加1
            Integer currentJoinedMembers = instEntity.getJoinedMembers();
            PatchGrouponInstEntity updateInstEntity =new PatchGrouponInstEntity();
            updateInstEntity.setId(instEntity.getId());
            updateInstEntity.setJoinedMembers(currentJoinedMembers +1);
            patchGrouponInstService.update(updateInstEntity);



        }

        innerResp.setLaunchOrJoinSuccess(Boolean.TRUE);
        return innerResp;
    }

    @Override
    public RestResult<PageResult<CurrentJoinedGrouponResponse>> currentJoinedGrouponList(CurrentJoinedGrouponRequest request) {
        if (request == null || request.getSpuId() == null){
            return null;
        }
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
        if (StringUtils.isNotEmpty(userStr)) {
            Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
            String userId = userMap.get("id").toString();
            request.setThirdUserId(userId);
        }
        log.info("------拼团活动H5服务--查询当前活动已开团未成团的列表--参数为:{}-------", request);

        //根据spuId查询sku编码
        RestResult<List<ProductStoreInfo>> restResult = productListApi.queryProductListBySpuId(request.getSpuId());
        List<String> skuCodeList = Lists.newArrayList();
        if (restResult != null && restResult.getData() != null && CollectionUtils.isNotEmpty(restResult.getData())){
            skuCodeList = restResult.getData().stream().map(ProductStoreInfo::getCode).collect(Collectors.toList());
        }

        PatchGrouponDetailEntity detailCondition =new PatchGrouponDetailEntity();
        List<Integer> statusList =new ArrayList<>();
        statusList.add(GrouponDetailPaymentStatusEnum.PAY_NOT.getCode());
        statusList.add(GrouponDetailPaymentStatusEnum.PAY_HAVE.getCode());
        detailCondition.setPaymentStatusList(statusList);

        detailCondition.setGroupCode(request.getGroupCode());
        detailCondition.setThirdProductCode(request.getThirdProductCode());
        detailCondition.setThirdProductCodeList(skuCodeList);
        detailCondition.setThirdUserId(request.getThirdUserId());
        detailCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        List<PatchGrouponDetailEntity> detailEntityList = patchGrouponInstDetailService.findAll(detailCondition);
        List<String> instCodeList = detailEntityList.stream().map(PatchGrouponDetailEntity::getGrouponInstCode).collect(Collectors.toList());


        // 查询表  patch_groupon_inst 拼团编码 groupCode  第三方商品编码  thirdProductCode
        PatchGrouponInstEntity instCondition =new PatchGrouponInstEntity();
        instCondition.setGroupCode(request.getGroupCode());
        instCondition.setThirdProductCode(request.getThirdProductCode());
        Pagination page = Pagination.build(request.getStart(), request.getLimit());
        List<PatchGrouponInstEntity> instList = patchGrouponInstService.findOfPage(instCondition, page);
        Integer count = patchGrouponInstService.countOfPage(instCondition);
        List<PatchGrouponInstEntity> instListCollect = instList.stream()
                .filter(item -> ((!item.getThirdUserId().equals(request.getThirdUserId()))&&
                        instCodeList.stream().filter(s ->item.getGrouponInstCode().equals(s))
                                .collect(Collectors.toList()).size()<=0)
                )
                .collect(Collectors.toList());
        PageResult pageResult =new PageResult();
        pageResult.setRows(instListCollect);
        pageResult.setTotal(count);
        return RestResult.success(pageResult);
    }

    @Override
    public RestResult<LaunchGrouponDetailResponse> launchGrouponDetail(LaunchGrouponDetailRequest request) {
        log.info("------拼团活动H5服务--查询开团详情--参数:{}-----",request);
        LaunchGrouponDetailResponse innerResp =new LaunchGrouponDetailResponse();
        // 【步骤】校验是否成团   patch_groupon_inst  status
        PatchGrouponInstEntity instEntityCondition =new PatchGrouponInstEntity();
        instEntityCondition.setGrouponInstCode(request.getGrouponInstCode());
        // 通过拼团实例code 查询
        PatchGrouponInstEntity instEntity = patchGrouponInstService.queryEntity(instEntityCondition);
        if(instEntity !=null){
            innerResp.setThirdProductCode(instEntity.getThirdProductCode());
            innerResp.setTotalMembers(instEntity.getTotalMembers());
            innerResp.setJoinedMembers(instEntity.getJoinedMembers());
            innerResp.setLaunchTime(instEntity.getLaunchTime().getTime());
            if(instEntity.getExpireTime()!=null){
                innerResp.setExpireTime(instEntity.getExpireTime().getTime());
            }
            innerResp.setGroupCode(instEntity.getGroupCode());
            innerResp.setGrouponInstCode(instEntity.getGrouponInstCode());

            PatchGrouponDetailEntity detailCondition =new PatchGrouponDetailEntity();
            List<Integer> statusList =new ArrayList<>();
            statusList.add(GrouponDetailPaymentStatusEnum.PAY_NOT.getCode());
            statusList.add(GrouponDetailPaymentStatusEnum.PAY_HAVE.getCode());
            detailCondition.setPaymentStatusList(statusList);
            detailCondition.setGrouponInstCode(instEntity.getGrouponInstCode());
            detailCondition.setGroupCode(instEntity.getGroupCode());
//            detailCondition.setThirdProductCode(instEntity.getThirdProductCode());
            detailCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            List<PatchGrouponDetailEntity> detailEntityList = patchGrouponInstDetailService.findAll(detailCondition);
            List<GrouponInstDetailResp> innerRespDetailList =new ArrayList<>();
            detailEntityList.forEach(x ->{
                GrouponInstDetailResp item =new GrouponInstDetailResp();
                item.setThirdUserId(x.getThirdUserId());
                item.setHeadFlag(x.getHeadFlag());
                innerRespDetailList.add(item);
            });

            innerResp.setGrouponInstDetailList(innerRespDetailList);
        } else {
            log.info("------拼团活动H5服务--查询开团详情--无开团信息--拼团实例code:{}--活动编码:{}-----",request.getGrouponInstCode(), request.getGroupCode());
            throw new MarketException(MarketErrorCodeEnum.GROUP_NO_INST_INFO);
        }

        return RestResult.success(innerResp);
    }

    @Transactional
    @Override
    public PostPayGroupInstDetailResponse postPayGroupInstDetail(PostPayGroupInstDetailRequest request) {
        PostPayGroupInstDetailResponse response =new PostPayGroupInstDetailResponse();
        // 【步骤】 根据订单号， 和第三方用户id 查询  patch_groupon_detail 信息
        PatchGrouponDetailEntity detailEntityCondition =new PatchGrouponDetailEntity();
        detailEntityCondition.setThirdOrderCode(request.getThirdOrderCode());
        detailEntityCondition.setThirdUserId(request.getThirdUserId());
        PatchGrouponDetailEntity detailEntity = patchGrouponInstDetailService.queryEntity(detailEntityCondition);

        if (detailEntity == null){
            return null;
        }
        Long detailEntityId = detailEntity.getId();
        String grouponInstCode = detailEntity.getGrouponInstCode();
        String groupCode = detailEntity.getGroupCode();

        // 【步骤】 根据订单号， 和第三方用户id 修改  patch_groupon_detail    payment_status  为  2已支付
        PatchGrouponDetailEntity updateDetailEntity =new PatchGrouponDetailEntity();
        updateDetailEntity.setId(detailEntityId);
        updateDetailEntity.setPaymentStatus(GrouponDetailPaymentStatusEnum.PAY_HAVE.getCode());
        patchGrouponInstDetailService.updateEntity(updateDetailEntity);

        // 【步骤】 根据  活动实例编码  payment_status  2已支付 查询 patch_groupon_detail    数量为 A
        PatchGrouponDetailEntity detailCondition =new PatchGrouponDetailEntity();
        detailCondition.setPaymentStatus(GrouponDetailPaymentStatusEnum.PAY_HAVE.getCode());
        detailCondition.setGrouponInstCode(grouponInstCode);
        detailCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        List<PatchGrouponDetailEntity> detailEntityList = patchGrouponInstDetailService.findAll(detailCondition);
        Integer detailEntitySizeA =detailEntityList.size();

        // 【步骤】 通过拼团实例code 查询 patch_groupon_inst   total_members 值为 B
        PatchGrouponInstEntity instEntityCondition =new PatchGrouponInstEntity();
        instEntityCondition.setGrouponInstCode(grouponInstCode);
        PatchGrouponInstEntity instEntity = patchGrouponInstService.queryEntity(instEntityCondition);
        Integer totalMembersB = instEntity.getTotalMembers();

        // 【步骤】  如果 A ==B 则，修改patch_groupon_inst   status  3已成团   completed_time  为当前时间
        if(detailEntitySizeA.equals(totalMembersB)){
            PatchGrouponInstEntity updateInstEntity =new PatchGrouponInstEntity();
            updateInstEntity.setId(instEntity.getId());
            updateInstEntity.setStatus(GrouponInstStatusEnum.GROUPED.getCode());
            updateInstEntity.setCompletedTime(new Date());
            patchGrouponInstService.update(updateInstEntity);

            // 【步骤】 如果成团，则需要返回  成团用户列表  见返回
            List<PostPayGroupInstDetailInfo> detailInfoList =new ArrayList<>();
            detailEntityList.forEach(x ->{
                PostPayGroupInstDetailInfo item =new PostPayGroupInstDetailInfo();
                item.setThirdUserId(x.getThirdUserId());
                item.setGroupCode(x.getGroupCode());
                item.setThirdOrderCode(x.getThirdOrderCode());
                item.setGrouponInstCode(x.getGrouponInstCode());
                detailInfoList.add(item);
            });
            response.setDetailInfoList(detailInfoList);
        }
        return response;
    }

    @Transactional
    @Override
    public PostPayGroupInstDetailResponse cancelPayGroupInstDetail(CancelPayGroupInstDetailRequest request) {
        PostPayGroupInstDetailResponse response =new PostPayGroupInstDetailResponse();
        // 【步骤】 根据订单号， 和第三方用户id 查询  patch_groupon_detail 信息
        PatchGrouponDetailEntity detailEntityCondition =new PatchGrouponDetailEntity();
        detailEntityCondition.setThirdOrderCode(request.getThirdOrderCode());
        detailEntityCondition.setThirdUserId(request.getThirdUserId());
        PatchGrouponDetailEntity detailEntity = patchGrouponInstDetailService.queryEntity(detailEntityCondition);

        if (detailEntity == null){
            return null;
        }
        // 实例详情的主键
        Long detailEntityId = detailEntity.getId();
        // 实例的主键
        Long refPatchGrouponInst = detailEntity.getRefPatchGrouponInst();
        String grouponInstCode = detailEntity.getGrouponInstCode();
        String groupCode = detailEntity.getGroupCode();
        Integer headFlag = detailEntity.getHeadFlag();

        // 【步骤】 1. 如果是团长
        if(GrouponHeadFlagEnum.GROUP_HEAD.getCode().equals(detailEntity.getHeadFlag())){
            // 【步骤】 则根据 实例 的主键 更改拼团实例   状态为组团失败  表patch_groupon_inst     为 4 组团失败
            PatchGrouponInstEntity updateInstEntity =new PatchGrouponInstEntity();
            updateInstEntity.setId(refPatchGrouponInst);
            updateInstEntity.setStatus(GrouponInstStatusEnum.GROUP_FAIL.getCode());
            patchGrouponInstService.update(updateInstEntity);

            // 【步骤】 根据 实例详情的主键 修改 实例详情  支付状态为已失效  表patch_groupon_detail    payment_status  为  3 已失效
            PatchGrouponDetailEntity updateDetailEntity =new PatchGrouponDetailEntity();
            updateDetailEntity.setId(detailEntityId);
            updateDetailEntity.setPaymentStatus(GrouponDetailPaymentStatusEnum.LOSE_EFFECT.getCode());
            patchGrouponInstDetailService.updateEntity(updateDetailEntity);

            // 【步骤】 根据 实例code 查找 实例详情列表 列表只保留其他团员id     表patch_groupon_detail  返回列表  其他团员 id，及拼团实例编码
            PatchGrouponDetailEntity detailCondition =new PatchGrouponDetailEntity();
            List<Integer> paymentStatusList =new ArrayList<>();
            paymentStatusList.add(GrouponDetailPaymentStatusEnum.PAY_NOT.getCode());
            paymentStatusList.add(GrouponDetailPaymentStatusEnum.PAY_HAVE.getCode());
            detailCondition.setGrouponInstCode(grouponInstCode);
            detailCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            detailCondition.setPaymentStatusList(paymentStatusList);
            List<PatchGrouponDetailEntity> detailEntityList = patchGrouponInstDetailService.findAll(detailCondition);

            // 【步骤】 排除当前用户即团长
            List<PatchGrouponDetailEntity> otherUserList = detailEntityList.stream().filter(item ->
                    (!item.getThirdUserId().equals(request.getThirdUserId()))).collect(Collectors.toList());

            // 【步骤】 除团长外的  用户列表
            List<PostPayGroupInstDetailInfo> detailInfoList =new ArrayList<>();
            detailEntityList.forEach(x ->{
                PostPayGroupInstDetailInfo item =new PostPayGroupInstDetailInfo();
                item.setThirdUserId(x.getThirdUserId());
                item.setGroupCode(x.getGroupCode());
                item.setThirdOrderCode(x.getThirdOrderCode());
                item.setGrouponInstCode(x.getGrouponInstCode());
                detailInfoList.add(item);
            });
            response.setDetailInfoList(detailInfoList);
        }

        //【步骤】 2. 如果是团员
        else {
            //【步骤】 根据 实例详情的主键 修改  实例详情  支付状态为已失效
            //     表 patch_groupon_detail    payment_status  为  3 已失效
            PatchGrouponDetailEntity updateDetailEntity =new PatchGrouponDetailEntity();
            updateDetailEntity.setId(detailEntityId);
            updateDetailEntity.setPaymentStatus(GrouponDetailPaymentStatusEnum.LOSE_EFFECT.getCode());
            patchGrouponInstDetailService.updateEntity(updateDetailEntity);

            //【步骤】 根据 实例 的主键 查询 实例
            PatchGrouponInstEntity queryInstEntity =new PatchGrouponInstEntity();
            queryInstEntity.setId(refPatchGrouponInst);
            PatchGrouponInstEntity patchGrouponInstEntity = patchGrouponInstService.queryEntity(queryInstEntity);
            Integer joinedMembers = patchGrouponInstEntity.getJoinedMembers();

            //【步骤】 根据 实例 的主键 修改  参与人数  减1  表   patch_groupon_inst   joined_members  减1
            PatchGrouponInstEntity updateInstEntity =new PatchGrouponInstEntity();
            updateInstEntity.setId(refPatchGrouponInst);
            updateInstEntity.setJoinedMembers(joinedMembers -1);
            patchGrouponInstService.update(updateInstEntity);

        }

        return response;
    }

    @Override
    public RestResult<PageResult<QueryGroupProductListResponse>> queryGroupProductList(QueryGroupProductListRequest request) {
        //查询进行中的拼图商品 分页
        request.setStart((request.getStart() - 1) * request.getLimit());

        List<QueryGroupProductListResponse> rest = patchGrouponMpEntityMapper.queryProcessingProductPage(request);

        Long count = patchGrouponMpEntityMapper.queryProcessingProductCount();

        List<String> mpCodeList = rest.stream().map(QueryGroupProductListResponse::getMpCode).collect(Collectors.toList());


        //格式化商品信息
        List<ProductStoreInfo> productStoreInfos = productListApi.queryProductListByThirdProductCodes(new GoodsPageQueryRequest() {{
            setThirdProductCodes(mpCodeList);
        }});

        rest.stream().forEach(item->{
            List<ProductStoreInfo> productStoreInfo = productStoreInfos.stream().filter(product -> product.getId().equals(item.getMpId())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(productStoreInfo)) {
                item.setMpUrl(productStoreInfo.get(0).getPictureUrl());
            }
        });
        return RestResult.success(new PageResult<QueryGroupProductListResponse> (){{
            setRows(rest);
            setTotal(count);
        }});
    }

    @Override
    public RestResult<List<MyBargainResponse>> launchGrouponProductDetail(MyBargainRequest request) {
        List<MyBargainResponse> res = new ArrayList<>();
        List<MyBargain> list = myBargainMapper.query(new MyBargain() {{
            setBargainId(request.getBargainId());
        }});
        if(CollectionUtils.isNotEmpty(list)){
            list.stream().forEach(item->{
                MyBargainResponse response = new MyBargainResponse();
                BeanUtils.copyProperties(item,response);
                res.add(response);
            });
        }
        return RestResult.success(res);
    }

    /**
     * 查询开团详情
     *
     * @param request
     * @return
     */
    @Override
    public RestResult<CurrentJoinedGroupResponse> getCurrentJoinedGroupInfo(CurrentJoinedGrouponRequest request) {
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
        if (StringUtils.isNotEmpty(userStr)) {
            Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
            String userId = userMap.get("id").toString();
            request.setThirdUserId(userId);
        }
        PatchGrouponInstEntity requestEntity = new PatchGrouponInstEntity();
        requestEntity.setDeleteFlag(0);
        requestEntity.setGrouponInstCode(request.getGroupInstCode());
        PatchGrouponInstEntity patchGrouponInstEntity = patchGrouponInstService.queryEntity(requestEntity);
        CurrentJoinedGroupResponse groupResponse = new CurrentJoinedGroupResponse();
        if (null != patchGrouponInstEntity) {
            BeanUtils.copyProperties(this.assemblyGroupInformation(patchGrouponInstEntity,request.getThirdUserId()), groupResponse);
        }
        return RestResult.success(groupResponse);
    }

    /**
     * 我的拼团列表
     *
     * @param request
     * @return
     */
    @Override
    public RestResult<PageResult<GroupInfoResponse>> getMyGroupList(GrouponListRequest request) {
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
        if (StringUtils.isNotEmpty(userStr)) {
            Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
            String userId = userMap.get("id").toString();
            Pagination pagination = Pagination.build(request.getStart(), request.getLimit());
            PatchGrouponDetailEntity condition = new PatchGrouponDetailEntity();
            condition.setStatus(request.getGroupInstStatus());
            condition.setThirdUserId(userId);
            //查询所有进行中的拼团活动
            List<GroupInfoResponse> pageForRest = patchGrouponDetailEntityMapper.queryPage(condition, pagination);
            pageForRest.forEach(groupInfoResponse -> {
                RestResult<OrderDetailInfo> orderInfoByOrderNo = orderApi.getOrderInfoByOrderNo(groupInfoResponse.getThirdOrderCode());
                GroupProductResponse groupProductResponse = new GroupProductResponse();
                if (orderInfoByOrderNo.getData() != null) {
                    if (orderInfoByOrderNo.getData().getProductInfo() != null) {
                        groupProductResponse.setAvailablePrice(new BigDecimal(orderInfoByOrderNo.getData().getProductInfo().get(0).get("availablePrice")));
                        groupProductResponse.setMpName(orderInfoByOrderNo.getData().getProductInfo().get(0).get("name"));
                        groupProductResponse.setPictureUrl(orderInfoByOrderNo.getData().getProductInfo().get(0).get("pictureUrl"));
                    }
                }
                groupInfoResponse.setGroupProductResponse(groupProductResponse);
            });

            long total = patchGrouponDetailEntityMapper.count(condition);

            return RestResult.success(new PageResult<GroupInfoResponse>() {{
                setRows(pageForRest);
                setTotal(total);
            }});
        }
        return RestResult.success(new PageResult<GroupInfoResponse>() {{
            setRows(new ArrayList<>());
            setTotal(0);
        }});
    }

    @Override
    public RestResult<LaunchGrouponDetailResponse> queryLaunchGrouponOrderInfo(LaunchGrouponDetailRequest request) {
        if (StringUtils.isEmpty(request.getGroupCode()) || StringUtils.isEmpty(request.getOrderCode())){
            return RestResult.error("9999","活动编码或订单号为空");
        }
        LaunchGrouponDetailResponse detailResponse = patchGrouponDetailEntityMapper.queryLaunchGrouponOrderInfo(request);
        return RestResult.success(detailResponse);
    }


    /**
     * 组装拼团数据
     *
     * @param patchGroupInstEntity
     * @return
     */
    private CurrentJoinedGroupResponse assemblyGroupInformation(PatchGrouponInstEntity patchGroupInstEntity,String userId) {
        CurrentJoinedGroupResponse groupResponse = new CurrentJoinedGroupResponse();
        BeanUtils.copyProperties(patchGroupInstEntity, groupResponse);
        //查询活动详细信息
        // 先查询出主键id
        PatchGrouponThemeEntity patchGrouponThemeEntityQ = new PatchGrouponThemeEntity();
        patchGrouponThemeEntityQ.setGroupCode(patchGroupInstEntity.getGroupCode());
        PatchGrouponThemeEntity byId = patchGrouponThemeEntityMapper.query(patchGrouponThemeEntityQ);
        if (byId != null){
            if (byId.getGroupTimeType().equals(GroupTimeTypeEnum.TIME_NO_RESTRICT.getCode())){
                groupResponse.setExpireTime(byId.getEndTime().getTime());
            }else {
                groupResponse.setExpireTime(patchGroupInstEntity.getExpireTime() != null ? patchGroupInstEntity.getExpireTime().getTime() : null);
            }
        }
        groupResponse.setGroupInstCode(patchGroupInstEntity.getGrouponInstCode());
        groupResponse.setMemberId(patchGroupInstEntity.getCatptainId());

        // 还差拼团人数
        if (null != patchGroupInstEntity.getTotalMembers()) {
            groupResponse.setDifferenceMembers(
                    patchGroupInstEntity.getTotalMembers() - (patchGroupInstEntity.getJoinedMembers() == null ? 0 : patchGroupInstEntity.getJoinedMembers())
            );
        }

        // 返回拼团成员信息
        List<PatchGrouponDetailEntity> patchGrouponDetailEntities = patchGrouponDetailEntityMapper.queryByRefPatchGrouponInst(
                new PatchGrouponDetailEntity() {{
                    setRefPatchGrouponInst(patchGroupInstEntity.getId());
                }});
        // TODO 需调用会员查询会员头像
        List<GroupInstDetailResponse> groupInstDetailResponseList = new ArrayList<>();
        patchGrouponDetailEntities.forEach(patchGrouponDetailEntity -> {
            GroupInstDetailResponse groupInstDetailResponse = new GroupInstDetailResponse();
            groupInstDetailResponse.setMemberId(Long.valueOf(patchGrouponDetailEntity.getThirdUserId()));
            groupInstDetailResponse.setHeadFlag(patchGrouponDetailEntity.getHeadFlag());
            groupInstDetailResponseList.add(groupInstDetailResponse);
        });
        groupResponse.setGroupInstDetailResponseList(groupInstDetailResponseList);

        //返回订单信息和商品信息
        PatchGrouponDetailEntity patchGrouponDetailEntity = patchGrouponDetailEntityMapper.query(new PatchGrouponDetailEntity() {{
            setGrouponInstCode(patchGroupInstEntity.getGrouponInstCode());
            //setThirdUserId(userId);
        }});
        if (patchGrouponDetailEntity != null) {
            RestResult<OrderDetailInfo> orderInfoByOrderNo = orderApi.getOrderInfoByOrderNo(patchGrouponDetailEntity.getThirdOrderCode());
            if (orderInfoByOrderNo.getData() != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("buyTime", orderInfoByOrderNo.getData().getBuyTime());
                map.put("orderNo", orderInfoByOrderNo.getData().getOrderNo());
                map.put("receiverAddress", orderInfoByOrderNo.getData().getReceiverAddress());
                map.put("receiverName", orderInfoByOrderNo.getData().getReceiverName());
                map.put("receiverPhone", orderInfoByOrderNo.getData().getReceiverPhone());
                groupResponse.setOrderInfo(map);
                GroupProductResponse groupProductResponse = new GroupProductResponse();
                if (orderInfoByOrderNo.getData().getProductInfo() != null) {
                    groupProductResponse.setMpName(orderInfoByOrderNo.getData().getProductInfo().get(0).get("name"));
                    groupProductResponse.setMarketPrice(new BigDecimal(orderInfoByOrderNo.getData().getProductInfo().get(0).get("marketPrice")));
                    groupProductResponse.setAvailablePrice(new BigDecimal(orderInfoByOrderNo.getData().getProductInfo().get(0).get("availablePrice")));
                    groupProductResponse.setMpId(Long.valueOf(orderInfoByOrderNo.getData().getProductInfo().get(0).get("productId")));
                    groupProductResponse.setGoodsNum(orderInfoByOrderNo.getData().getProductInfo().get(0).get("goodsNum"));
                    groupProductResponse.setGoodsProperty(orderInfoByOrderNo.getData().getProductInfo().get(0).get("goodsProperty"));
                    groupProductResponse.setPictureUrl(orderInfoByOrderNo.getData().getProductInfo().get(0).get("pictureUrl"));
                    groupProductResponse.setStoreName(orderInfoByOrderNo.getData().getProductInfo().get(0).get("storeName"));
                    groupProductResponse.setStoreLogo(orderInfoByOrderNo.getData().getProductInfo().get(0).get("storeLogo"));
                }
                groupResponse.setGroupProductResponse(groupProductResponse);
            }
        }

        return groupResponse;
    }
}
